// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Text;
using Antlr4.Runtime.Misc;
using Templating.Grammar.Antlr;
using static Templating.Grammar.Antlr.TemplatingParser;

namespace SnapObjects.Data
{
    internal partial class DataTemplateParser
        : TemplatingParserBaseVisitor<StringBuilder>
        , ITemplatingParserVisitor<StringBuilder>
    {
        public override StringBuilder VisitExpr([NotNull] ExprContext context)
        {
            var text = context.TOKEN_EXPR().GetText();

            var expr = text.Trim();

            if (String.IsNullOrWhiteSpace(expr) ||
                !this.TryGetExpression(expr, out expr))
            {
                return _builder.Append(text);
            }

            var hasDefaultValue = false;
            string defaultValue = null;
            var defaultValueIndex = expr.LastIndexOf("??");

            if (defaultValueIndex > -1 && defaultValueIndex < expr.Length)
            {
                hasDefaultValue = true;

                if (defaultValueIndex < expr.Length - 2)
                {
                    defaultValue = expr.Substring(defaultValueIndex + 2).TrimStart();

                    defaultValue = _dataFormat.Format(defaultValue)?.ToString();
                }

                expr = expr.Remove(defaultValueIndex);
                if (String.IsNullOrWhiteSpace(expr))
                {
                    return _builder.Append(defaultValue);
                }
            }

            try
            {
                var result = _dataProvider.Evaluate(expr, _context.Model);

                return _builder.Append(result);
            }
            catch (SyntaxErrorException) when (hasDefaultValue)
            {
                return _builder.Append(defaultValue);
            }
            catch (Exception)
            {
                var data = _dataFormat.Format(expr);
                
                return _builder.Append(data);
            }
        }

        public override StringBuilder VisitPartial([NotNull] PartialContext context)
        {
            var partial = context.TOKEN_PARTIAL().GetText();

            if (!this.TryGetExpression(partial, out var name) ||
                String.IsNullOrWhiteSpace(name))
            {
                return _builder.Append(name);
            }

            var value = _dataProvider.Partial(name, _context.Model);

            return _builder.Append(value);
        }

        private bool TryGetExpression(string raw, out string expr)
        {
            var result = _exprRegex.Match(raw);

            if (result.Success)
            {
                expr = result.Groups[1].Value;

                return true;
            }

            expr = null;

            return false;
        }

        public override StringBuilder VisitParentPart([NotNull] ParentPartContext context)
        {
            _builder.Append(context.TOKEN_OP_LBRACKET().GetText());

            var expressions = context.part();

            Array.ForEach(expressions, x => this.Visit(x));

            //this.Visit(context.part());

            return _builder.Append(context.TOKEN_OP_RBRACE().GetText());
        }
    }
}
